<?php
namespace Base;

abstract class BaseOrmObject implements \ArrayAccess
{
    //--------------------------------------------------------------------------------------------//
    //	functions to implemet for ArrayAccess
    //--------------------------------------------------------------------------------------------//
    public final function offsetSet($offset, $value)
    {
        $this->{$offset} = $value;
    }

    public final function offsetExists($offset)
    {
        return isset($this->{$offset});
    }

    public final function offsetUnset($offset)
    {
        unset($this->{$offset});
    }

    public final function offsetGet($offset)
    {
        return isset($this->{$offset}) ? $this->{$offset} : null;
    }

    public function __init($data)
    {
        if (empty($data)) {
            return;
        }
        foreach ($data as $k => $v) {
            if (property_exists($this, $k)) {
                $this->{$k} = $v;
            }
        }
    }


    protected function setBackupData($fields = array())
    {
        $tmp = array('origin' => array(),
            'change' => array()
        );
        if ($fields) // insert/ update
        {
            foreach ($fields as $k) {
                if (isset($this->backup_data[$k])) {
                    if ($this->backup_data[$k] != $this->{$k}) {
                        $tmp['origin'][$k] = $this->backup_data[$k];
                        $tmp['change'][$k] = $this->{$k};
                    }
                } else {
                    $tmp['change'][$k] = $this->{$k};
                }
            }
            $this->backup_data = $tmp;
        } else // delete
        {
            $tmp['origin'] = $this->backup_data;
            $this->backup_data = $tmp;
        }
    }

    public function beginTransaction()
    {
        $model = new \Base\BaseOrmModel();
        return $model->beginTransaction();
    }

    public function commit()
    {
        $model = new \Base\BaseOrmModel();
        return $model->commit();
    }

    public function rollBack()
    {
        $model = new \Base\BaseOrmModel();
        return $model->rollBack();
    }


    final function objToArray($obj){
        $array = array();
        if (is_object($obj)) {
            foreach ($obj as $key=>$value) {
                $array[$key] = $value;
            }
        }
        return $array;
    }
}